package com.numkit.briefdraw.tool;

import java.io.File;
import java.util.Hashtable;
import java.util.Iterator;

public class TempFilePool {
	private String fileNameHead = "";

	private String fileNameTail = "";

	private static final int MAX_FILE_NUMBER = 1000;

	private Hashtable htFile = new Hashtable();

	private String tempDir = null;

	public TempFilePool() throws Exception {
		tempDir = System.getProperties().getProperty("java.io.tmpdir");
		if (tempDir == null)
			throw new Exception("Can't init TempFilePool, tmpdir not found!");
		File dirFile = new File(tempDir);
		if (!(dirFile.isDirectory() && dirFile.exists()))
			throw new Exception("Can't init TempFilePool, tmpdir not exist!");
	}

	public File getFile(String strID) throws Exception {
		File file = null;
		file = (File) htFile.get(strID);
		if (file == null) {
			file = createFile();
			htFile.put(strID, file);
		}
		return file;
	}

	public void deleteFile(String strID) throws Exception {
		File file = (File) htFile.get(strID);
		if (file == null)
			throw new Exception("The file according to strID not exist!");
		if (file.exists()) {
			if (!file.delete())
				throw new Exception("Failed to delete the file!");
		}
		htFile.remove(strID);
	}

	public void clearPool() throws Exception {
		for (Iterator i = htFile.values().iterator(); i.hasNext();) {
			File file = (File) i.next();
			if (file.exists()) {
				if (!file.delete())
					throw new Exception("Clear File Pool failed!");
			}
		}
		htFile.clear();
	}

	private File createFile() throws Exception {
		File file = null;
		int i = 0;
		while (true) {
			file = new File(tempDir + fileNameHead + i + fileNameTail);
			if (!file.exists()) {
				file.createNewFile();
				break;
			} else {
				i++;
				if (i >= MAX_FILE_NUMBER)
					throw new Exception("File number in the pool reach to max!");
			}
		}
		return file;
	}

	public String getFileNameHead() {
		return fileNameHead;
	}

	public void setFileNameHead(String fileNameHead) {
		this.fileNameHead = fileNameHead;
	}

	public String getFileNameTail() {
		return fileNameTail;
	}

	public void setFileNameTail(String fileNameTail) {
		this.fileNameTail = fileNameTail;
	}
	
	
}
